#include "StdAfx.h"
#include "FileRecvManager.h"
#include <QDir>
#include <QApplication>

FileRecvManager::FileRecvManager()
{
	srcFileDB = QSharedPointer<FileDB>(new FileDB);
	curTransferFileIndex = 0;
	QString dstPath = QApplication::applicationDirPath() + "\\dst";
	dstPath = QDir::toNativeSeparators(dstPath);

//	srcFileDB->SetPath("C:\\Users\\Administrator\\Desktop\\Project\\Seven\\dst");
	srcFileDB->SetPath(dstPath);
}

FileRecvManager::~FileRecvManager()
{
	Reset();
}

void FileRecvManager::SetPathTable(const seven::PathTable* table )
{
	srcFileDB->SetPathTable(table);
}

void FileRecvManager::SetFileTable(const seven::FileTable* table )
{
	srcFileDB->SetFileTable(table);
	const FileDB::FileInfoTableType& fileInfo =  srcFileDB->GetFileInfoTable();
	fileFinished.fill(false,fileInfo.size());
}

void FileRecvManager::RequireFiles()
{
	if (curTransferFileIndex >= fileFinished.size())
	{
		emit TransferFinish();
		return;
	}
	else
	{
		emit RequireFile(curTransferFileIndex);
	}
}

void FileRecvManager::RecvFile( int fileId,const char* buff,int size )
{
	srcFileDB->CreateFile(fileId);
	srcFileDB->Write(fileId,0,buff,size);

	++curTransferFileIndex;
	RequireFiles();
}

void FileRecvManager::SetPath( const QString& path )
{
	recvPath = path;
}

void FileRecvManager::RecvFileBlock( int fileId, int blockIndex, char* buff, int size )
{
	srcFileDB->CreateFile(fileId);
	srcFileDB->Write(fileId,blockIndex * fileBlockSize ,buff,size);
}

void FileRecvManager::Start()
{
	srcFileDB->CreateDirs();
	RequireFiles();
}

void FileRecvManager::Reset()
{
	srcFileDB.clear();
	fileFinished.clear();
	curTransferFileIndex = 0;
	recvPath = "";
}
